package com.daxt.utils;

import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class WordUtil {

    private final static Logger log = LoggerFactory.getLogger(WordUtil.class);


    public static void searchAndReplace(String srcPath, String destPath,
                                        Map<String, Object> map) {
        try {
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(srcPath));
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                //String s = paragraph.getParagraphText();
                Set<String> set = map.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    List<XWPFRun> run = paragraph.getRuns();
                    for (int i = 0; i < run.size(); i++) {
                        if (run.get(i).getText(run.get(i).getTextPosition()) != null && run.get(i).getText(run.get(i).getTextPosition()).contains("{" + key + "}")) {
                            String replace = run.get(i).getText(run.get(i).getTextPosition()).replace("{" + key + "}", map.get(key).toString());
                            run.get(i).setText(replace, 0);
                        }
                    }
                }
            }

            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
                XWPFTable table = (XWPFTable) itTable.next();
                int rcount = table.getNumberOfRows();
                for (int i = 0; i < rcount; i++) {
                    XWPFTableRow row = table.getRow(i);
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (int j = 0; j < cells.size(); j++) {
                        for (Entry<String, Object> e : map.entrySet()) {
                            if (cells.get(j).getText().contains("{" + e.getKey() + "}")) {
                                //cell.removeParagraph(0);
                                String text = cells.get(j).getText();
                                String replace = text.replace("{" + e.getKey() + "}", e.getValue() == null ? "" : e.getValue().toString());
                                cells.get(j).removeParagraph(0);
                                cells.get(j).setText(replace);
                            }
                        }
                    }
                }
            }
            FileOutputStream outStream = null;
            outStream = new FileOutputStream(destPath);
            document.write(outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void searchAndAppend(String srcPath, String destPath,
                                       List<Map<String, Object>> map, Map<String, Object> map1) {
        try {
            XWPFDocument document = new XWPFDocument(
                    POIXMLDocument.openPackage(srcPath));
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                //String s = paragraph.getParagraphText();
                Set<String> set = map1.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    List<XWPFRun> run = paragraph.getRuns();
                    for (int i = 0; i < run.size(); i++) {
                        if (run.get(i).getText(run.get(i).getTextPosition()) != null && run.get(i).getText(run.get(i).getTextPosition()).contains("{" + key + "}")) {

                            String replace = run.get(i).getText(run.get(i).getTextPosition()).replace("{" + key + "}", map1.get(key) == null ? "" : map1.get(key).toString());
                            run.get(i).setText(replace, 0);
                        }
                    }
                }
            }

            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {

                XWPFTable table = (XWPFTable) itTable.next();
                int rcount = table.getNumberOfRows();
                int index = 0;
                int cellCount = 0;
                XWPFTableRow temp = null;
                for (int i = 0; i < map.size(); i++) {

                    XWPFTableRow row = table.getRow(i);
                    List<XWPFTableRow> rows = table.getRows();
                    for (int k = 0; k < rows.size(); k++) {
                        List<XWPFTableCell> cells = rows.get(k).getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            for (Entry<String, Object> e : map.get(i).entrySet()) {
                                if (cells.get(j).getText().contains("{" + e.getKey() + "}")) {
                                    index = k;
                                    cellCount = cells.size();
                                    temp = rows.get(k);
                                }
                            }
                        }
                    }


                }
                if (index > 0) {
                    for (int j = 0; j < map.size(); j++) {
                        //XWPFTableRow createRow = table.createRow();

                        CTRow ctrow = CTRow.Factory.parse(temp.getCtRow().newInputStream());
                        XWPFTableRow newRow = new XWPFTableRow(ctrow, table);
                        List<XWPFTableCell> tableCells = newRow.getTableCells();
                        int f = 0;
                        for (int k = 0; k < tableCells.size(); k++) {
                            XWPFTableCell cell = tableCells.get(k);
                            for (XWPFParagraph p : cell.getParagraphs()) {
                                for (XWPFRun r : p.getRuns()) {
                                    if (f == 0) {
                                        r.setText(j + 1 + "", 0);
                                    } else {
                                        String text = r.getText(0);
                                        Set<String> keySet = map.get(j).keySet();
                                        for (String key : keySet) {
                                            if (text.trim().equals(("{" + key + "}"))) {
                                                r.setText(map.get(j).get(key) == null ? "" : map.get(j).get(key).toString(), 0);
                                            }
                                        }
                                        if (r.getText(0).startsWith("{") || r.getText(0).startsWith("}"))
                                            r.setText("", 0);
                                    }
                                }
                            }
                            f++;
                            //System.out.println(cell.getText());
                        }
                        table.addRow(newRow, rcount);
                        rcount++;
                    }
                    table.removeRow(rcount - map.size() - 1);
                }
            }

            FileOutputStream outStream = null;
            outStream = new FileOutputStream(destPath);
            document.write(outStream);
            outStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean toPdf(String path, String tarPath) {
        try {
            Runtime run = Runtime.getRuntime();
            //String cmd ="cmd /c soffice --headless --invisible --convert-to pdf "+path+" --outdir "+tarPath;
            String cmd = null;
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
//                cmd = "cmd /c soffice --headless --invisible --convert-to pdf " + path + " --outdir " + tarPath;
                cmd = "cmd /c soffice --headless --invisible --convert-to pdf " + path + " --outdir " + tarPath;
            } else {
                cmd = "/usr/bin/libreoffice7.1 soffice --headless --invisible --convert-to pdf " + path + " --outdir " + tarPath;
            }
            System.out.println(cmd);
            log.info("========toPdf====command=====");
            log.info(cmd);
            Process p = run.exec(cmd);
            int i = p.waitFor();
            if (i == 0) return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

//		public static void main(String[] args){
//            Runtime run = Runtime.getRuntime();
//            String cmd = "cmd /c soffice --headless --invisible --convert-to pdf D:\\1111.xlsx --outdir D:\\home\\jar\\temp\\";
////            String cmd = "cmd /c cd C:\\Program Files\\LibreOffice\\program\\ && soffice --headless --invisible --convert-to pdf D:\\home\\jar\\temp\\14071711366339665941407171136633966595.xls --outdir D:\\home\\jar\\temp\\";
//
//
//            try {
////                Process process = Runtime.getRuntime().exec("ping www.baidu.com");
//                Process process = Runtime.getRuntime().exec(cmd);
//                try {
//                    if(process.waitFor() == 0){
//                        System.out.println("D:\\juan.pdf");
//                    }else{
//                        System.out.println("操作失败");
//                    }
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//                System.out.println("任务执行完毕！");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
////            try {
////                Process p = run.exec(cmd);
////                p.waitFor();
////                System.out.println("pdf地址：D:\\home\\jar\\temp\\14071711366339665941407171136633966595.pdf");
////            } catch (IOException e) {
////                e.printStackTrace();
////            } catch (InterruptedException e) {
////                e.printStackTrace();
////            }
//
//        }


    public static void main(String[] args) {
//        int ll = 15;
//        int ll_1 = ll + 1;
//        int ll_2 = ll * 2;
//        int ll_2_1 = ll_2 + 1;
////            String str1 = "if(length(A8)>31){return substring(A8,30,31)}";
////            String str2 = "else if(length(A8)<32 and length(A8)>=1){return substring(A8,0,1)}";
////            String str1 = "if(length(A8)>31){return substring(A8,30,31)}";
////            String str2 = "else if(length(A8)<32 and length(A8)>1){return substring(A8,0,1)}";
//
//
//        for (int i = 0; i <= ll; i++) {
//            System.out.println("=========" + (i + 1) + "========");
//            System.out.println("中");
//            System.out.println("if(length(A8)>" + (ll + i) + "){return substring(A8," + (ll + i) + "," + (ll_1 + i) + ")}");
//            System.out.println("else if(length(A8)<=" + ll + " and length(A8)>=" + (i + 1) + "){return substring(A8," + i + "," + (i + 1) + ")}");
//
//            System.out.println("右");
//            System.out.println("if(length(A8)>" + ll + "){return substring(A8," + i + "," + (i + 1) + ")}");
//
//            System.out.println("左");
//            System.out.println("if(length(A8)>" + (ll_2 + i) + "){return substring(A8," + (ll_2 + i) + "," + (ll_2_1 + i) + ")}");
//        }

//        String str = "select substring('阿斯顿飞过',1,1) as 'name',substring('abcdefghijklmnopqrstuvwxyz',1,1) as 'title_R',substring('abcdefghijklmnopqrstuvwxyz',24,1) as 'title_C'  " +
//                "UNION ALL";

        String name = "t.ext09";
        String title = "t.title";
//        String name = "'阿斯顿飞过'";
//        String title = "abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyz";
//        int i = 1;
        int row = 22;
//        String str = "select substring('"+name+"',"+i+",1) as 'name',substring('"+title+"',"+i+",1) as 'title_R',substring('"+title+"',"+row+",1) as 'title_C'  " +
//                "UNION ALL";

        for(int i = 1;i < row+1; i++){
            String str = "select substring("+name+","+i+",1) as 'name',substring("+title+","+i+",1) as 'title_R',substring("+title+","+(row+i)+",1) as 'title_C',substring("+title+","+(row*2+i)+",1) as 'title_L',t.id from archives_doc t where t.id in (:dossierIds)  ";
            System.out.println(str);
            System.out.println("UNION ALL");

        }






    }

}
